import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ToolsService} from "@shared/service/tools/tools.service";
import {Subject} from "rxjs/Subject";
import {SaleService} from "@sale/sale.service";

import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {AuthService} from "@shared/service/auth/auth.service";
import {ValidationService} from "@shared/service/validator/validator.service";
import {TrainClassessVO, TrainSaleSignFormRespVo, TrainSchoolSimpleVO, TrainTimesCourseRespVO} from "@interface/index";
// import {
//   TrainClassessVO, TrainSaleSignFormRespVo, TrainSchoolSimpleVO,
//   TrainTimesCourseRespVO
// } from "@interface/sale/sale.model";

@Component({
  selector: 'seed-apply-registration',
  templateUrl: './apply-registration.component.html',
  styleUrls: ['./apply-registration.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ApplyRegistrationComponent implements OnInit {
  private ngUnsubscribe: Subject<any> = new Subject<any>();
  public pageForm: FormGroup; // 表单对象
  public pageData = {
    orgUserId: '', // 组织ID
    studentId: '', // 学员ID
    saleUserId: '', // 销售人员ID
    timesCourseCode: '', // 次课CODE
    buyTypeList: [{
      id: '2',
      title: '次卡'
    }, {
      id: '0,1',
      title: '普通班'
    }],
    payTypeList: [{
      id: '1',
      title: '现金'
    }, {
      id: '2',
      title: '刷卡'
    }, {
      id: '3',
      title: '支付宝'
    }, {
      id: '4',
      title: '微信'
    }]
  };
  public courseList: Array<TrainSaleSignFormRespVo>; // 课程列表
  public simpleVOList: Array<TrainSchoolSimpleVO> = []; // 校区列表
  public trainClassessVOS: Array<TrainClassessVO> = []; // 班级列别
  public trainTimesCourseRespVOS: Array<TrainTimesCourseRespVO> = []; // 次课列表

  constructor(private toolsService: ToolsService,
              private service: SaleService,
              private route: ActivatedRoute,
              private router: Router,
              private formBuilder: FormBuilder,
              private authService: AuthService) {
    // 初始化表单
    this.pageForm = this.formBuilder.group({
      'buyType': ['', [Validators.required]],
      'payType': ['', [Validators.required]],
      'signupFee': ['', [Validators.required, ValidationService.moneyValidator()]],
      'courseId': ['', [Validators.required]],
      'schoolId': ['', [Validators.required]],
      'classesId': ['', [Validators.required]]
    });

    // 选择购课类型事件
    this.pageForm.controls.buyType.valueChanges.distinctUntilChanged().subscribe(res => {
      this.operationInput();
      this.getCourseList();
    });

    // 选择课程事件
    this.pageForm.controls.courseId.valueChanges.distinctUntilChanged().subscribe(res => {
      const tempArray = [];
      this.courseList.filter((item) => {
        if (item.trainCourseSimpleVO.id === Number.parseInt(res)) {
          this.simpleVOList = item.simpleVOList;
          this.trainClassessVOS = item.trainClassessVOS;
          item.trainTimesCourseRespVOS.filter((value) => {
            // 剔除体验课，体验课的 code 以 T 开头， 次课以 c 开头
            if (value.timesCourseCode && value.timesCourseCode.indexOf('T') === -1) {
              tempArray.push(value);
            }
          });
          this.trainTimesCourseRespVOS = tempArray;
          this.emptySelect('curriculum');
        }
      });
    });
  }

  /**
   * 获取课程动态表单
   */
  public getCourseList() {
    this.service.getCourseFormList(this.pageData.orgUserId, this.pageForm.controls.buyType.value)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (this.checkResult(res)) {
        this.courseList = res.data;
        this.emptySelect('buyType');
      }
    });
  }

  /**
   * 提交报名信息
   */
  public submitInfo() {
    const formParams = {
      orgUserId: this.pageData.orgUserId,
      studentId: this.pageData.studentId,
      saleUserId: this.pageData.saleUserId,
      ...this.pageForm.value
    };
    if (formParams.buyType !== '2') {
      formParams.buyType = '1';
    }
    formParams.signupFee = formParams.signupFee * 100;
    this.toolsService.showLoading();
    this.service.applyRegistration(formParams).takeUntil(this.ngUnsubscribe).subscribe(res => {
      this.toolsService.hideLoading();
      if (this.checkResult(res)) {
        // this.toolsService.showToast(res.msg);
        setTimeout(() => {
          history.back();
        }, 1500);
      }
    });
  }

  /**
   * 清空选择框
   */
  private emptySelect(status: string) {
    // 购课类型更改选项清空
    if (status === 'buyType') {
      this.pageForm.controls.courseId.setValue('');
      this.simpleVOList = [];
      this.trainClassessVOS = [];
    }

    // 课程更改选项清空
    this.pageForm.controls.schoolId.setValue('');
    this.pageForm.controls.classesId.setValue('');

    // 次课清空
    if (this.pageForm.value.buyType === 2) {
      this.trainTimesCourseRespVOS = [];
      this.pageForm.controls.timesCourseCode.setValue('');
    }
  }

  /**
   * 根据情况创建或移除input
   */
  private operationInput() {
    if (this.pageForm.controls.buyType.value === '2') {
      this.pageForm.removeControl('timesCourseCode');
      this.pageForm.addControl('timesCourseCode', new FormControl('', [Validators.required]));
    } else {
      this.pageForm.removeControl('timesCourseCode');
    }
  }

  /**
   *检查返回状态
   */
  public checkResult(res) {
    if (res.result !== '0') {
      this.toolsService.showToast(res.msg);
    }
    return res.result === '0';
  }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.pageData.orgUserId = this.authService.getAuthOrgId();
      this.pageData.studentId = params['studentId'];
      this.pageData.saleUserId = params['saleUserId'];
    });
  }
}
